/**
 * 组合UDP包的线程
 * 包组合后，将压缩 的图像数据解压缩
 */
package com.jahentao.integrationTest.case03.client;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import javax.swing.Icon;
import javax.swing.ImageIcon;

import com.jahentao.integrationTest.case03.common.Packet;
import com.jahentao.integrationTest.case03.common.ScreenHandler;


/**
 * @author jahen
 * @date 2016年8月6日
 * @time 下午11:27:16
 * @category Socket编程
 */
public class CombineScreenThread extends Thread {
	
	private long time;
	private int packetNum;
	private ScreenHandler handler;
	private ArrayList<Packet> packetList;
	
	public CombineScreenThread(long time, int packetNum, ScreenHandler handler) {
		this.time = time;
		this.packetNum = packetNum;
		this.handler = handler;
		packetList =  new ArrayList<Packet>(packetNum);
	}
	/**
	 * 添加一个Packet包
	 */
	public void add(Packet packet){
		packetList.add(packet);
	}
	public int getSize() {
		synchronized (packetList) { //临界区变量
			return packetList.size();
		}
	}
	public long getTime() {
		return time;
	}

	@Override
	public void run() {
		while(true){
			if(getSize()==packetNum)
				break;
		}
		// 包集齐了就排个序
		packetList.sort(new Comparator<Packet>() {
			@Override
			public int compare(Packet o1, Packet o2) {
				return o1.getOrder()-o2.getOrder();
			}
		});
		// 组装帧画面
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		try {
			for(int i=0; i<packetNum; i++) {
				baos.write(packetList.get(i).getData());
			}
			baos.close();
		}catch(Exception e){
			e.printStackTrace();
		}
		// 获得压缩的图像数据
		byte[] frameZipedData = baos.toByteArray();
		// 对图像数据解压缩
		ByteArrayInputStream bais = new ByteArrayInputStream(frameZipedData);
		ZipInputStream zis = new ZipInputStream(bais);
		ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
		
		try {
			ZipEntry nextEntry = null;
			if((nextEntry=zis.getNextEntry())!=null){ // 只有一个条目
				int len = -1;
				byte[] buffer = new byte[1024];
				while((len=zis.read(buffer))!=-1)
					baos2.write(buffer, 0, len);
			}
			nextEntry.clone();
			zis.close();
			baos2.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		byte[] frameData = baos2.toByteArray();
		
		Icon icon = new ImageIcon(frameData);
		handler.getThreadMap().remove(time);
		handler.getFrameQueue().add(icon);
	}
}
